<template>
  <div class="create-order-container">
    <h2 class="page-title">确认订单</h2>
    
    <el-card class="order-info">
      <template #header>
        <div class="card-header">
          <span>活动信息</span>
        </div>
      </template>
      
      <div class="event-info" v-if="eventInfo">
        <div class="event-image">
          <el-image :src="eventInfo.coverUrl" fit="cover" :preview-src-list="coverPreviewList" />
        </div>
        <div class="event-detail">
          <h3>{{ eventInfo.title }}</h3>
          <p class="event-time">时间：{{ eventInfo.startTime }} ~ {{ eventInfo.endTime }}</p>
          <p class="event-location">地点：{{ eventInfo.location }}</p>
        </div>
      </div>
      
      <!-- 票种信息 -->
      <div class="ticket-info">
        <h4>票种信息</h4>
        <el-table :data="ticketItems" border stripe>
          <el-table-column label="票种名称" prop="ticketName" />
          <el-table-column label="单价" prop="price">
            <template #default="scope">
              <span class="price">¥ {{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="quantity" width="200">
            <template #default="scope">
              <el-input-number v-model="scope.row.quantity" :min="1" :max="10" @change="calculateTotal" />
            </template>
          </el-table-column>
          <el-table-column label="小计" prop="subtotal">
            <template #default="scope">
              <span class="subtotal">¥ {{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 联系人信息 -->
      <div class="contact-info">
        <h4>联系人信息</h4>
        <el-form ref="contactForm" :model="contactInfo" :rules="contactRules" label-width="100px" status-icon>
          <el-form-item label="姓名" prop="name">
            <el-input 
              v-model="contactInfo.name" 
              placeholder="请输入联系人姓名" 
              clearable
              show-word-limit
              maxlength="20"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input 
              v-model="contactInfo.phone" 
              placeholder="请输入联系人手机号" 
              clearable
              maxlength="11"
            />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input 
              v-model="contactInfo.email" 
              placeholder="请输入联系人邮箱" 
              clearable
            />
          </el-form-item>
          <el-form-item label="出生日期" prop="birthDate">
            <el-date-picker 
              v-model="contactInfo.birthDate" 
              type="date" 
              placeholder="请选择出生日期"
              :disabled-date="disableFutureDates"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="国家" prop="country">
            <el-select 
              v-model="contactInfo.country" 
              placeholder="请选择国家"
              filterable
              clearable
            >
              <el-option v-for="country in countries" :key="country" :label="country" :value="country" />
            </el-select>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input 
              v-model="contactInfo.address" 
              type="textarea" 
              :rows="2" 
              placeholder="请输入详细地址" 
              show-word-limit
              maxlength="100"
            />
          </el-form-item>
          <el-form-item label="邮政编码" prop="zipCode">
            <el-input 
              v-model="contactInfo.zipCode" 
              placeholder="请输入邮政编码" 
              clearable
              maxlength="6"
            />
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 支付方式 -->
      <div class="payment-method">
        <h4>支付方式</h4>
        <el-form :model="paymentInfo" :rules="paymentRules" label-width="100px">
          <el-form-item label="支付方式" prop="method">
            <el-radio-group v-model="paymentInfo.method">
              <el-radio label="wechat">微信支付</el-radio>
              <el-radio label="alipay">支付宝</el-radio>
              <el-radio label="creditcard">银行卡支付</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <!-- 银行卡支付信息 -->
          <div v-if="paymentInfo.method === 'creditcard'" class="card-info">
            <el-form-item label="卡号" prop="cardNumber">
              <el-input v-model="paymentInfo.cardNumber" placeholder="请输入银行卡号" />
            </el-form-item>
            <el-form-item label="持卡人" prop="cardHolder">
              <el-input v-model="paymentInfo.cardHolder" placeholder="请输入持卡人姓名" />
            </el-form-item>
          </div>
        </el-form>
      </div>
      
      <!-- 订单总计 -->
      <div class="order-total">
        <div class="total-amount">
          总计：<span class="price">¥ {{ totalAmount.toFixed(2) }}</span>
        </div>
        
        <!-- 模拟支付输入框 -->
        <div class="payment-simulation">
          <el-input-number 
            v-model="paymentAmount" 
            :precision="2" 
            :step="10" 
            :min="0" 
            controls-position="right"
            placeholder="请输入支付金额"
            style="width: 200px; margin-right: 10px;"
            :disabled="submitting || submitSuccess"
          />
          <el-button 
            type="primary" 
            size="default" 
            @click="verifyPayment"
            :disabled="submitting || !paymentAmount || submitSuccess"
          >
            {{ paymentVerified ? '已验证' : '验证金额' }}
          </el-button>
        </div>
        
        <el-button type="primary" size="large" @click="submitOrder" :loading="submitting" :disabled="!paymentVerified || submitting || submitSuccess">
          <template v-if="submitting">正在提交订单...</template>
          <template v-else-if="submitSuccess">订单提交成功</template>
          <template v-else-if="!paymentVerified">请先验证金额</template>
          <template v-else>提交订单</template>
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createOrder } from '@/api/order'
import { getFrontEventDetail, getFrontEventTickets } from '@/utils/apiAdapter'

const route = useRoute()
const router = useRouter()
const eventId = route.query.eventId
const ticketId = route.query.ticketId

// 国家列表
const countries = ref([
  '中国', '美国', '英国', '加拿大', '澳大利亚', '日本', '韩国', '法国', '德国',
  '意大利', '西班牙', '俄罗斯', '新加坡', '马来西亚', '泰国', '印度', '巴西',
  '南非', '埃及', '其他'
])

// 活动信息
const eventInfo = ref(null)
// 票种列表
const ticketItems = ref([])
// 封面图片预览列表
const coverPreviewList = computed(() => {
  if (eventInfo.value && eventInfo.value.coverUrl) {
    return [eventInfo.value.coverUrl]
  }
  return []
})
// 联系人信息
const contactInfo = ref({
  name: '',
  phone: '',
  email: '',
  address: '',
  zipCode: '',
  birthDate: '',
  country: ''
})
// 支付信息
const paymentInfo = ref({
  method: 'wechat', // 默认微信支付
  cardNumber: '',
  cardHolder: ''
})
// 表单验证规则
const contactRules = {
  name: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在2到20个字符之间', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z\s·]+$/, message: '姓名只能包含中文、英文字母和空格', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系人手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码格式', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入联系人邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址格式', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '邮箱格式不正确', trigger: 'blur' }
  ],
  birthDate: [
    { required: true, message: '请选择出生日期', trigger: 'change' },
    { validator: (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择出生日期'));
      } else {
        const today = new Date();
        const selectedDate = new Date(value);
        
        // 检查是否是未来日期
        if (selectedDate > today) {
          callback(new Error('出生日期不能是未来日期'));
          return;
        }
        
        // 检查年龄是否在合理范围（例如，120岁以内）
        const maxAge = 120;
        const minDate = new Date();
        minDate.setFullYear(today.getFullYear() - maxAge);
        
        if (selectedDate < minDate) {
          callback(new Error(`出生日期不合理，年龄不应超过${maxAge}岁`));
          return;
        }
        
        callback();
      }
    }, trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '地址长度在5到100个字符之间', trigger: 'blur' }
  ],
  country: [
    { required: true, message: '请选择国家', trigger: 'change' },
    { validator: (rule, value, callback) => {
      if (!value || value === '') {
        callback(new Error('请选择国家'));
      } else {
        callback();
      }
    }, trigger: 'change' }
  ],
  zipCode: [
    { required: true, message: '请输入邮政编码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入正确的6位数字邮政编码', trigger: 'blur' }
  ]
}
// 支付方式验证规则
const paymentRules = {
  method: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ],
  cardNumber: [
    { required: true, message: '请输入银行卡号', trigger: 'blur', validator: (rule, value, callback) => {
      if (paymentInfo.value.method === 'creditcard' && !value) {
        callback(new Error('请输入银行卡号'));
      } else {
        callback();
      }
    }}
  ],
  cardHolder: [
    { required: true, message: '请输入持卡人姓名', trigger: 'blur', validator: (rule, value, callback) => {
      if (paymentInfo.value.method === 'creditcard' && !value) {
        callback(new Error('请输入持卡人姓名'));
      } else {
        callback();
      }
    }}
  ]
}

// 提交状态
const submitting = ref(false)
const submitSuccess = ref(false)
const contactForm = ref(null)

// 计算总金额
const totalAmount = computed(() => {
  let total = 0
  ticketItems.value.forEach(item => {
    total += item.price * item.quantity
  })
  return total
})

// 支付相关变量
const paymentAmount = ref(0)
const paymentVerified = ref(false)

// 验证支付金额
const verifyPayment = () => {
  if (!paymentAmount.value) {
    ElMessage.warning('请输入支付金额')
    return
  }
  
  const expectedAmount = totalAmount.value
  const inputAmount = paymentAmount.value
  
  if (Math.abs(inputAmount - expectedAmount) < 0.01) {
    // 金额正确（考虑浮点数精度问题）
    paymentVerified.value = true
    ElMessage.success('金额验证成功！')
  } else if (inputAmount < expectedAmount) {
    // 金额不足
    ElMessage.error(`支付金额不足！应付金额: ¥${expectedAmount.toFixed(2)}，差额: ¥${(expectedAmount - inputAmount).toFixed(2)}`)
    paymentVerified.value = false
  } else {
    // 金额超出
    ElMessage.warning(`支付金额超出！应付金额: ¥${expectedAmount.toFixed(2)}，多支付: ¥${(inputAmount - expectedAmount).toFixed(2)}`)
    paymentVerified.value = false
  }
}

// 禁用未来日期
const disableFutureDates = (time) => {
  return time.getTime() > Date.now();
}

// 获取活动详情
const fetchEventDetail = async () => {
  try {
    const res = await getFrontEventDetail(eventId)
    if (res.code === 200 && res.data) {
      console.log('获取到活动详情:', res.data)
      eventInfo.value = res.data
      
      // 确保coverUrl存在，如果不存在则使用cover
      if (!eventInfo.value.coverUrl && eventInfo.value.cover) {
        eventInfo.value.coverUrl = eventInfo.value.cover
      }
      console.log('处理后的活动图片URL:', eventInfo.value.coverUrl)
    } else {
      ElMessage.error('获取活动详情失败')
    }
  } catch (error) {
    console.error('获取活动详情出错:', error)
    ElMessage.error('获取活动详情失败')
  }
}

// 获取票种信息
const fetchTickets = async () => {
  try {
    const res = await getFrontEventTickets(eventId)
    console.log('获取票种信息响应:', res)
    
    if (res.code === 200 && res.data) {
      console.log('原始票种数据:', res.data)
      
      // 确保票种数据是数组
      if (!Array.isArray(res.data)) {
        console.error('票种数据不是数组格式:', res.data)
        ElMessage.error('票种数据格式不正确')
        return
      }
      
      // 如果没有票种数据
      if (res.data.length === 0) {
        console.warn('未获取到票种数据')
        ElMessage.warning('该活动暂无可用票种')
        return
      }
      
      // 放宽过滤条件：只要有库存就显示，不强制要求status为1
      let availableTickets = res.data.filter(ticket => {
        // 计算剩余数量
        const remainingQuantity = ticket.remainingQuantity !== undefined ? 
                                ticket.remainingQuantity : 
                                (ticket.totalStock || 0) - (ticket.soldCount || 0)
        
        // 如果有剩余库存则视为可用
        const available = remainingQuantity > 0
        
        console.log(`票种[${ticket.name || ticket.id}] 状态:${ticket.status}, 剩余:${remainingQuantity}, 是否可用:${available}`)
        return available
      })
      
      // 如果过滤后没有可用票种，则尝试显示所有票种，让用户自行选择
      if (availableTickets.length === 0) {
        console.warn('过滤后没有可用票种，显示全部票种')
        availableTickets = res.data
      }
      
      // 如果有指定的票种ID，则只添加该票种
      if (ticketId) {
        console.log(`尝试查找指定票种ID: ${ticketId}`)
        const selectedTicket = availableTickets.find(t => t.id == ticketId)
        if (selectedTicket) {
          console.log('找到指定票种:', selectedTicket)
          ticketItems.value = [
            {
              id: selectedTicket.id,
              ticketName: selectedTicket.name,
              price: selectedTicket.price || 0, // 确保价格字段存在
              quantity: 1,
              remainingQuantity: selectedTicket.remainingQuantity !== undefined ?
                                selectedTicket.remainingQuantity :
                                (selectedTicket.totalStock || 0) - (selectedTicket.soldCount || 0)
            }
          ]
        } else {
          console.warn(`未找到ID为${ticketId}的票种，将显示所有可用票种`)
          ticketItems.value = availableTickets.map(ticket => ({
            id: ticket.id,
            ticketName: ticket.name || `票种${ticket.id}`, // 确保有票种名称
            price: ticket.price || 0, // 确保价格字段存在
            quantity: 1,
            remainingQuantity: ticket.remainingQuantity !== undefined ?
                              ticket.remainingQuantity :
                              (ticket.totalStock || 0) - (ticket.soldCount || 0)
          }))
        }
      } else {
        // 否则添加所有可用票种
        console.log('未指定票种ID，显示所有可用票种')
        ticketItems.value = availableTickets.map(ticket => ({
          id: ticket.id,
          ticketName: ticket.name || `票种${ticket.id}`, // 确保有票种名称
          price: ticket.price || 0, // 确保价格字段存在
          quantity: 1,
          remainingQuantity: ticket.remainingQuantity !== undefined ?
                            ticket.remainingQuantity :
                            (ticket.totalStock || 0) - (ticket.soldCount || 0)
        }))
      }
      
      console.log('最终票种列表:', ticketItems.value)
    } else {
      console.error('获取票种失败:', res.msg || '未知错误')
      ElMessage.error(res.msg || '获取票种信息失败')
    }
  } catch (error) {
    console.error('获取票种信息出错:', error)
    ElMessage.error('获取票种信息失败')
  }
}

// 计算总额
const calculateTotal = () => {
  // 触发计算属性更新
  console.log('计算总金额:', totalAmount.value)
}

// 验证整个表单
const validateForm = () => {
  if (contactForm.value) {
    return new Promise((resolve) => {
      contactForm.value.validate((valid) => {
        if (valid) {
          resolve(true);
        } else {
          ElMessage.warning('请正确填写所有必填信息');
          resolve(false);
        }
      });
    });
  }
  return Promise.resolve(false);
};

// 格式化订单数据
const formatOrderData = () => {
  // 确保所有必填字段存在
  if (!contactInfo.value.name || !contactInfo.value.phone || !contactInfo.value.email) {
    throw new Error('请完善联系人信息');
  }
  
  // 格式化生日日期，确保是YYYY-MM-DD格式
  let formattedBirthDate = contactInfo.value.birthDate;
  if (formattedBirthDate && typeof formattedBirthDate === 'object') {
    formattedBirthDate = formattedBirthDate.toISOString().split('T')[0];
  }
  
  return {
    // 基本信息
    eventId: parseInt(eventId),
    
    // 联系人信息
    contactName: contactInfo.value.name.trim(),
    contactPhone: contactInfo.value.phone.trim(),
    contactEmail: contactInfo.value.email.trim(),
    address: contactInfo.value.address.trim(),
    zipCode: contactInfo.value.zipCode.trim(),
    birthDate: formattedBirthDate,
    country: contactInfo.value.country,
    
    // 支付信息
    paymentMethod: paymentInfo.value.method,
    paymentAmount: paymentAmount.value,
    paymentDetails: paymentInfo.value.method === 'creditcard' ? {
      cardNumber: paymentInfo.value.cardNumber.trim(),
      cardHolder: paymentInfo.value.cardHolder.trim()
    } : null,
    
    // 票种信息
    tickets: ticketItems.value.map(item => ({
      ticketId: item.id,
      quantity: item.quantity,
      price: item.price,
      subtotal: (item.price * item.quantity).toFixed(2)
    })),
    
    // 订单总额
    totalAmount: totalAmount.value.toFixed(2)
  };
};

// 提交订单
const submitOrder = async () => {
  // 检查是否验证过支付金额
  if (!paymentVerified.value) {
    ElMessage.warning('请先验证支付金额')
    return
  }
  
  // 表单验证
  const valid = await validateForm();
  if (!valid) {
    return;
  }
  
  // 检查票种数量
  if (ticketItems.value.length === 0) {
    ElMessage.warning('请选择至少一种票种')
    return
  }
  
  // 确认提交
  try {
    await ElMessageBox.confirm('确认提交订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    submitting.value = true
    submitSuccess.value = false
    
    // 构建订单数据，确保包含所有联系人字段
    let orderData;
    try {
      orderData = formatOrderData();
    } catch (error) {
      ElMessage.error(error.message);
      submitting.value = false;
      return;
    }
    
    console.log('提交订单数据:', orderData)
    
    // 显示加载提示
    const loadingInstance = ElMessage({
      message: '正在提交订单，请稍候...',
      type: 'info',
      duration: 0,
      showClose: false
    });
    
    // 发送请求到 http://localhost:5902/api/front/orders/create
    try {
      const res = await createOrder(orderData)
      console.log('订单创建响应:', res)
      
      // 关闭加载提示
      loadingInstance.close();
      
      if (res.code === 200 && res.data) {
        submitSuccess.value = true;
        
        // 显示成功消息
        ElMessage({
          message: '订单创建并支付成功! 2秒后跳转到订单列表...',
          type: 'success',
          duration: 2000,
          showClose: true,
          onClose: () => {
            // 跳转到订单列表页面
            router.push({
              path: '/front/user/orders'
            });
          }
        });
        
        // 2秒后自动跳转
        setTimeout(() => {
          if (submitSuccess.value) {
            router.push({
              path: '/front/user/orders'
            });
          }
        }, 2000);
      } else {
        // 提供更详细的错误信息
        const errorMsg = res.msg || '创建订单失败';
        console.error('订单创建失败:', errorMsg);
        ElMessage({
          message: errorMsg,
          type: 'error',
          duration: 5000,
          showClose: true
        });
      }
    } catch (error) {
      // 关闭加载提示
      loadingInstance.close();
      
      console.error('提交订单出错:', error);
      let errorMessage = '提交订单失败，请稍后重试';
      
      // 尝试提取更具体的错误信息
      if (error.response && error.response.data) {
        errorMessage = error.response.data.msg || errorMessage;
      } else if (error.message) {
        errorMessage = error.message;
      }
      
      ElMessage({
        message: errorMessage,
        type: 'error',
        duration: 5000,
        showClose: true
      });
    } finally {
      submitting.value = false
    }
  } catch (e) {
    // 用户取消提交
    console.log('用户取消提交订单')
  }
}

// 监听联系人信息变化，实时验证
const validateField = (field) => {
  // 确保表单已经初始化
  if (contactForm.value) {
    contactForm.value.validateField(field);
  }
};

// 为每个字段添加监听
watch(() => contactInfo.value.name, (val) => {
  if (val && val.length >= 2) {
    validateField('name');
  }
});

watch(() => contactInfo.value.phone, (val) => {
  if (val && val.length === 11) {
    validateField('phone');
  }
});

watch(() => contactInfo.value.email, (val) => {
  if (val && val.includes('@')) {
    validateField('email');
  }
});

watch(() => contactInfo.value.birthDate, (val) => {
  if (val) {
    validateField('birthDate');
  }
});

watch(() => contactInfo.value.country, (val) => {
  if (val) {
    validateField('country');
  }
});

watch(() => contactInfo.value.address, (val) => {
  if (val && val.length >= 5) {
    validateField('address');
  }
});

watch(() => contactInfo.value.zipCode, (val) => {
  if (val && val.length === 6) {
    validateField('zipCode');
  }
});

// 页面加载时获取数据
onMounted(() => {
  if (!eventId) {
    ElMessage.error('未指定活动ID')
    router.push('/front/event/list')
    return
  }
  
  fetchEventDetail()
  fetchTickets()
})
</script>

<style scoped>
.create-order-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  color: #303133;
}

.order-info {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.event-info {
  display: flex;
  margin-bottom: 20px;
}

.event-image {
  width: 200px;
  height: 120px;
  margin-right: 20px;
  overflow: hidden;
  border-radius: 4px;
}

.event-detail {
  flex: 1;
}

.event-time, .event-location {
  color: #606266;
  line-height: 1.8;
}

.ticket-info, .contact-info, .payment-method {
  margin-bottom: 30px;
}

.price, .subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.order-total {
  display: flex;
  flex-direction: column;
  gap: 15px;
  align-items: flex-end;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.total-amount {
  font-size: 18px;
}

.total-amount .price {
  font-size: 22px;
}

.payment-simulation {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.card-info {
  margin-top: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}
</style> 